<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Search, Delete, Plus, Stamp, QuartzWatch, Watch } from '@element-plus/icons-vue'
import { type AmsPlugin, type AddPluginDto, type UpdatePluginDto } from '@/api/ams'
import { getPluginList, addPlugin, deletePlugin, updatePlugin, getUploadFileUri } from '@/api/ams'
import type { UploadProps } from 'element-plus'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'

defineOptions({
  name:"Plugin"
})

const searchDto = reactive({
  name: '',
})
const tableData = ref<AmsPlugin[]>([])
const isAddDialog = ref(true) // 是否为添加模式
const showDialog = ref(false) // 是否显示模态框
const dialogForm = reactive<AmsPlugin>({})
const checkStatus = ref<string[]>([])
const headers = {
  authorization: getToken(),
}

const clickSearchBtn = () => {
  getPluginList().then((res) => {
    tableData.value = res
  })
}
onMounted(() => {
  clickSearchBtn()
})

const clickAddBtn = () => {
  isAddDialog.value = true
  dialogForm.id = '0'
  dialogForm.name = ''
  dialogForm.description = ''
  dialogForm.source = 'miao'
  dialogForm.downloadUrl = ''
  dialogForm.unTarget = ''
  dialogForm.version = ''
  dialogForm.md5 = ''
  dialogForm.zipMd5 = ''
  dialogForm.isRequired = false
  dialogForm.checkMd5 = false
  dialogForm.checkVersion = false
  checkStatus.value = []
  showDialog.value = true
}
const clickEditBtn = (row: AmsPlugin) => {
  isAddDialog.value = false
  dialogForm.id = row.id
  dialogForm.name = row.name
  dialogForm.description = row.description
  dialogForm.source = row.source
  dialogForm.downloadUrl = row.downloadUrl
  dialogForm.unTarget = row.unTarget
  dialogForm.version = row.version
  dialogForm.md5 = row.md5
  dialogForm.zipMd5 = row.zipMd5
  if (row.isRequired) {
    checkStatus.value.push('isRequired')
  }
  if (row.checkMd5) {
    checkStatus.value.push('checkMd5')
  }
  if (row.checkVersion) {
    checkStatus.value.push('checkVersion')
  }
  dialogForm.isRequired = checkStatus.value.includes('isRequired')
  dialogForm.checkMd5 = checkStatus.value.includes('checkMd5')
  dialogForm.checkVersion = checkStatus.value.includes('checkVersion')
  showDialog.value = true
}

const clickDelBtn = (id: string) => {
  deletePlugin(id).then(() => {
    clickSearchBtn()
  })
}

const clickSubDialogForm = () => {
  if (isAddDialog.value) {
    // 添加
    const addData: AddPluginDto = {
      name: dialogForm.name,
      description: dialogForm.description,
      source: dialogForm.source,
      downloadUrl: dialogForm.downloadUrl,
      unTarget: dialogForm.unTarget,
      version: dialogForm.version,
      md5: dialogForm.md5,
      zipMd5: dialogForm.zipMd5,
      checkVersion: dialogForm.checkVersion,
      checkMd5: dialogForm.checkMd5,
      isRequired: dialogForm.isRequired,
    }
    addData.isRequired = checkStatus.value.includes('isRequired')
    addData.checkMd5 = checkStatus.value.includes('checkMd5')
    addData.checkVersion = checkStatus.value.includes('checkVersion')
    addPlugin(addData).then(() => {
      clickSearchBtn()
    })
  } else {
    // 更新
    const updateData: UpdatePluginDto = {
      id: dialogForm.id,
      name: dialogForm.name,
      description: dialogForm.description,
      source: dialogForm.source,
      downloadUrl: dialogForm.downloadUrl,
      unTarget: dialogForm.unTarget,
      version: dialogForm.version,
      md5: dialogForm.md5,
      zipMd5: dialogForm.zipMd5,
      checkVersion: false,
      checkMd5: false,
      isRequired: false,
    }
    updateData.isRequired = checkStatus.value.includes('isRequired')
    updateData.checkMd5 = checkStatus.value.includes('checkMd5')
    updateData.checkVersion = checkStatus.value.includes('checkVersion')
    updatePlugin(updateData).then(() => {
      clickSearchBtn()
    })
  }
  showDialog.value = false
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log(response, uploadFile)
  dialogForm.name = uploadFile.name.replaceAll('.zip', '')
  dialogForm.downloadUrl = response.filename
  dialogForm.md5 = response.pluginMd5
  dialogForm.zipMd5 = response.zipMd5
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type !== 'application/x-zip-compressed') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  }
  return true
}
</script>

<template>
  <div>
    <el-dialog v-model="showDialog" :title="isAddDialog ? '添加插件' : '更新插件'" width="500">
      <el-form :model="dialogForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="" v-show="isAddDialog" class="up-file-item">
          <el-upload
            class="avatar-uploader"
            :headers="headers"
            name="file"
            :action="getUploadFileUri()"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dialogForm.description" />
        </el-form-item>
        <el-form-item label="来源">
          <el-select v-model="dialogForm.source" placeholder="Select">
            <el-option key="miao" label="miao" value="miao" />
            <el-option key="win" label="win" value="win" />
            <el-option key="linux" label="linux(开发中)" value="linux" :disabled="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="下载地址">
          <el-input v-model="dialogForm.downloadUrl" />
        </el-form-item>
        <el-form-item label="释放路径">
          <el-input v-model="dialogForm.unTarget" />
        </el-form-item>
        <el-form-item label="版本">
          <el-input v-model="dialogForm.version" />
        </el-form-item>
        <el-form-item label="文件MD5">
          <el-input v-model="dialogForm.md5" />
        </el-form-item>
        <el-form-item label="压缩包MD5">
          <el-input v-model="dialogForm.zipMd5" />
        </el-form-item>
        <el-form-item label="必须检查">
          <el-checkbox-group v-model="checkStatus">
            <el-checkbox value="isRequired" name="type"> 必须 </el-checkbox>
            <el-checkbox value="checkMd5" name="type"> MD5 </el-checkbox>
            <el-checkbox value="checkVersion" name="type"> 版本号 </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="clickSubDialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-row>
      <el-col>
        <el-card>
          <el-row class="mb-5">
            <el-col>
              <el-input
                v-model="searchDto.name"
                class="max-w-xs mr-5"
                placeholder="请输入插件名称"
                clearable
              />
              <el-button type="primary" :icon="Search" @click="clickSearchBtn">查询</el-button>
              <el-button type="primary" :icon="Plus" @click="clickAddBtn">添加</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" stripe style="width: 100%" show-overflow-tooltip>
            <el-table-column type="index" width="50" label="#" />
            <el-table-column prop="name" label="名称" width="100" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="source" label="来源" width="50" />
            <el-table-column prop="downloadUrl" label="下载地址" width="120" />
            <el-table-column prop="unTarget" label="解压地址" width="120" />
            <el-table-column prop="version" label="版本" width="80" />
            <el-table-column prop="zipMd5" label="压缩包MD5" width="250" />
            <el-table-column prop="md5" label="文件MD5" width="250" />
            <el-table-column prop="md5" label="检查方式" width="80">
              <template #default="scope">
                <el-tooltip content="是否为必须插件，缺失时会自动触发文件下载" placement="top">
                  <el-link
                    :icon="Stamp"
                    :type="scope.row.isRequired ? 'success' : 'info'"
                  ></el-link>
                </el-tooltip>
                <el-tooltip content="是否检查MD5，MD5不同时自动触发更新" placement="top">
                  <el-link
                    :icon="QuartzWatch"
                    :type="scope.row.checkMd5 ? 'success' : 'info'"
                  ></el-link>
                </el-tooltip>
                <el-tooltip content="是否检查版本号，版本号不同时自动触发更新" placement="top">
                  <el-link
                    :icon="Watch"
                    :type="scope.row.checkVersion ? 'success' : 'info'"
                  ></el-link>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="100">
              <template #default="scope">
                {{ dayjs(new Date(scope.row.createdAt * 1000)).format('YYYY-MM-DD') }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="130">
              <template #default="scope">
                <el-link :icon="Edit" type="primary" class="mr-3" @click="clickEditBtn(scope.row)"
                  >修改</el-link
                >
                <el-link
                  :icon="Delete"
                  type="primary"
                  class="mr-3"
                  @click="clickDelBtn(scope.row.id)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
:deep(.up-file-item .el-form-item__content) {
  display: flex;
  justify-content: center;
}
:deep(.avatar) {
  width: 80px;
  height: 80px;
}
:deep(.avatar-uploader .el-upload) {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}
:deep(.el-icon.avatar-uploader-icon) {
  font-size: 80px;
  color: #8c939d;
  text-align: center;
}
</style>
